﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions;
using UnityEngine.UI;

namespace Nirvana
{
    /// <summary>
    /// 用于toggle切换指定image的图片
    /// </summary>
    [AddComponentMenu("Nirvana/UI/Control/Toggle Sprite")]
    [RequireComponent(typeof(Toggle))]
    public sealed class ToggleSprite : MonoBehaviour
    {
        [SerializeField]
        [Tooltip("The image target to change.")]
        private Image target;

        [SerializeField]
        [Tooltip("The sprite changed when toggled.")]
        private Sprite toggledSprite;

        private Toggle toggle;
        private Sprite defaultSprite;

        private void OnValueChanged(bool isOn)
        {
            if (this.target != null)
            {
                this.target.sprite = ((!isOn) ? this.defaultSprite : this.toggledSprite);
            }
        }

        private void Awake()
        {
            this.toggle = base.GetComponent<Toggle>();
            Assert.IsNotNull<Toggle>(this.toggle);
            if (this.target != null)
            {
                this.defaultSprite = this.target.sprite;
            }
            this.OnValueChanged(this.toggle.isOn);
            this.toggle.onValueChanged.AddListener(OnValueChanged);
        }
        private void OnDestroy()
        {
            if (this.toggle != null)
            {
                this.toggle.onValueChanged.RemoveListener(OnValueChanged);
            }
        }

    }
}

